package lex.util;

import javax.swing.SwingConstants;

import org.lex.utils.text.Splitter;


/**
 * The <code>Fvwm</code> class specifies constraints for components that are
 * laid out using the <code>FvwmLayout</code> class.
 */
public class Fvwm {
	/**
	 * available values of <code>anchor</code>
	 */
	public static final int TOP = SwingConstants.TOP;
	public static final int CENTER = SwingConstants.CENTER;
	public static final int BOTTOM = SwingConstants.BOTTOM;
	/**
	 * available values of <code>from</code>
	 */
	public static final int LEFT = SwingConstants.LEFT;
	public static final int RIGHT = SwingConstants.RIGHT;
	public int from;
	public int offset;
	public int anchor;

	public Fvwm() {
		this(LEFT, 0, CENTER);
	}

	public Fvwm(int from, int x, int anchor) {
		this.from = from;
		this.offset = x;
		this.anchor = anchor;
	}

	public String toString() {
		StringBuilder b = new StringBuilder();
		if (LEFT == from)
			b.append("LEFT");
		else
			b.append("RIGHT");
		b.append(' ');
		if (TOP == anchor)
			b.append("TOP");
		else if (CENTER == anchor)
			b.append("CENTER");
		else if (BOTTOM == anchor)
			b.append("BOTTOM");
		b.append(' ').append(offset);
		return b.toString();
	}

	public static Fvwm valueOf(String str) {
		if (null == str || 0 == str.length())
			return null;
		str = str.trim().toLowerCase();
		if (0 == str.length())
			return null;
		String[] tokens = Splitter.BlankSpaceSplitter.split(str);
		if (null == tokens || 0 == tokens.length)
			return null;
		Fvwm c = new Fvwm();
		for (int i = 0; i < tokens.length; i++) {
			String s = tokens[i];
			int v = isOffset(s);
			if (-1 != v) {
				c.offset = v;
				continue;
			}
			v = isFrom(s);
			if (-1 != v) {
				c.from = v;
				continue;
			}
			v = isAnchor(s);
			if (-1 != v) {
				c.anchor = v;
			}
		}
		return c;
	}

	// ===================================================
	static String DECIMAL_DIGIT = "0123456789";

	static int isOffset(String str) {
		for (int i = 0; i < str.length(); i++)
			if (-1 == DECIMAL_DIGIT.indexOf(str.charAt(i)))
				return -1;
		return Integer.parseInt(str);
	}

	static int isFrom(String str) {
		if (str.equals("left"))
			return LEFT;
		else if (str.equals("right"))
			return RIGHT;
		else
			return -1;
	}

	static int isAnchor(String str) {
		if (str.equals("top"))
			return TOP;
		else if (str.equals("center"))
			return CENTER;
		else if (str.equals("bottom"))
			return BOTTOM;
		else
			return -1;
	}
}
